<?php


	namespace app\services;


	use app\lib\exception\ToastException;

	class SubscribeMessageServices
	{

		const LIST_URL = 'https://api.weixin.qq.com/wxaapi/newtmpl/gettemplate?access_token=%s';

		const CATEGORY_URL = 'https://api.weixin.qq.com/wxaapi/newtmpl/getcategory?access_token=%s';

		const SEND_URL = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=%s';

		private $access_token;

		public function __construct () {
			$this->access_token = AccessTokenServices::getAccessToken();
		}

		//模板列表
		public function getTemplateList () {
			$url = sprintf(self::LIST_URL, $this->access_token);
			$ret = json_decode(file_get_contents($url),true);

			if (array_key_exists('errcode', $ret) && $ret['errcode'] != 0) {
				throw new ToastException($ret['errmsg']);
			}

			return $ret['data'];
		}
		//类目
		public function getCategory () {
			$url = sprintf(self::CATEGORY_URL, $this->access_token);

			$ret = json_decode(file_get_contents($url), true);

			if (array_key_exists('errcode', $ret) && $ret['errcode'] != 0) {
				throw new ToastException($ret['errmsg']);
			}

			return $ret['data'];
		}
		//发送订阅消息
		public function send ($touser, $template_id, $data, $page = false) {
			$url = sprintf(self::SEND_URL, $this->access_token);
			$send_data = [
				'touser'      => $touser,
				'template_id' => $template_id,
				'data'        => $data
			];

			if ($page) {
				$send_data['page'] = $page;
			}

			$ret = json_decode(postHttps($url, json_encode($send_data)),true);

			if (array_key_exists('errcode', $ret) && $ret['errcode'] != 0) {
				throw new ToastException($ret['errmsg']);
			}

			return true;
		}
	}
